package backgroud;


/**
 * @author Brook
 *
 * 第二种线程安全问题，死锁
 */
public class MultiDedeThreadError implements Runnable{

    int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();


    @Override
    public void run() {
        System.out.println("flag = +" + flag);
        if(flag == 1) {
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName()+":获取到锁o1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName()+":获取到锁o2");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName()+":获取到锁o2");
                try {
                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName()+":获取到锁o1");
                }

            }
        }

    }

    public static void main(String[] args) {
        MultiDedeThreadError r1 = new MultiDedeThreadError();
        MultiDedeThreadError r2 = new MultiDedeThreadError();
        r1.flag = 1;
        r2.flag = 0;

        Thread thread1 = new Thread(r1);

        Thread thread2 = new Thread(r2);
        thread1.start();
        thread2.start();
    }
}
